#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <unistd.h>
#include "lesson9_线程池/log.hpp"

void Usage(std::string filename)
{
    std::cout << "./Usage " << filename << " ip port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string ip = argv[1];
    uint16_t port = atoi(argv[2]);
    std::string line;

    struct sockaddr_in client;
    bzero(&client, sizeof client);

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        exit(2);
    }

    client.sin_family = AF_INET;
    client.sin_port = htons(port);
    client.sin_addr.s_addr = inet_addr(ip.c_str());

    if (connect(sock, (struct sockaddr *)&client, sizeof client) < 0)
    {
        exit(3);
    }

    std::cout << "connect success" << std::endl;

    while (true)
    {
        std::cout << "请输入# ";
        std::getline(std::cin, line);
        if (line == "quit")
            break;

        ssize_t s = send(sock, line.c_str(), line.size(), 0);
        if (s > 0)
        {
            char buffer[1024];
            ssize_t s = recv(sock, buffer, sizeof(buffer) - 1, 0);
            if (s > 0)
            {
                buffer[s] = 0;
                std::cout << "server 回显# " << buffer << std::endl;
            }
            else if (s == 0)
            {
                close(sock);
            }
        }
        else
        {
            close(sock);
        }
    }

    return 0;
}
